package cn.itsource.ymcc.listener;

import cn.itsource.ymcc.constant.MQ;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQTransactionListener(
        txProducerGroup = MQ.YMCC_COURSE_ORDER_PAY_PRODUCER
)
public class CourseOrderMessageListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 执行本地事务
     * @param msg
     * @param arg 获取的是sendMessageInTransaction方法的第四个参数
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            log.info("事务消息监听器：正在执行本地事务......");
            CourseOrder courseOrder = (CourseOrder) arg;
            //执行保存订单和订单明细：保证保存订单及订单明细和推送消息的原子性，要么全部成功，要么全部失败
            courseOrderService.insert(courseOrder);
            //通知MQ：当前消息可以被消费了
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            //通知MQ：当前消息作废
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 检查本地事务
     *  当上面这个executeLocalTransaction方法返回RocketMQLocalTransactionState.UNKNOWN时才会执行这个检查
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        log.info("事务消息监听器：正在检查本地事务......");
        return null;
    }
}
